//
//  SHKSohu.m
//  WSJJ_iPad
//
//  Created by lian jie on 1/27/11.
//  Copyright 2011 2009-2010 Dow Jones & Company, Inc. All rights reserved.
//

#import "SHKSohu.h"
#import "SHKSohuForm.h"
@implementation SHKSohu

@synthesize xAuth;
@synthesize delegate;

- (id)init{
	if ((self = [super init])){	
		// OAUTH		
		self.consumerKey = SHKSohuKey;		
		self.secretKey = SHKSohuSecret;
 		self.authorizeCallbackURL = [NSURL URLWithString:SHKSohuCallbackUrl];// HOW-TO: In your Twitter application settings, use the "Callback URL" field.  If you do not have this field in the settings, set your application type to 'Browser'.
		
		// XAUTH
		self.xAuth = NO;
		
		// You do not need to edit these, they are the same for everyone
	    self.authorizeURL = [NSURL URLWithString:@"http://api.t.sohu.com/oauth/authorize"];
	    self.requestURL = [NSURL URLWithString:@"http://api.t.sohu.com/oauth/request_token"];
	    self.accessURL = [NSURL URLWithString:@"http://api.t.sohu.com/oauth/access_token"]; 
	}	
	return self;
}


#pragma mark -
#pragma mark Configuration : Service Defination

+ (NSString *)sharerTitle{
	return @"搜狐微博";
}

+ (BOOL)canShareURL{
	return YES;
}

+ (BOOL)canShareText{
	return YES;
}

// TODO use img.ly to support this
//+ (BOOL)canShareImage
//{
//	return YES;
//}


#pragma mark -
#pragma mark Configuration : Dynamic Enable

- (BOOL)shouldAutoShare{
	return NO;
}


#pragma mark -
#pragma mark Authorization

- (BOOL)isAuthorized{		
	return [self restoreAccessToken];
}

- (void)promptAuthorization{		
	if (xAuth){
		[super authorizationFormShow]; // xAuth process
	}else{
		[super promptAuthorization]; // OAuth process		
	}
}


#pragma mark xAuth

+ (NSString *)authorizationFormCaption{
	return @"创建一个搜狐微博帐号";
}

+ (NSArray *)authorizationFormFields{
	return [NSArray arrayWithObjects:
			[SHKFormFieldSettings label:@"用户名" key:@"username" type:SHKFormFieldTypeText start:nil],
			[SHKFormFieldSettings label:@"密码" key:@"password" type:SHKFormFieldTypePassword start:nil],		
			nil];
}

- (void)authorizationFormValidate:(SHKFormController *)form{
	self.pendingForm = form;
	[self tokenAccess];
}
- (void)tokenRequestModifyRequest:(OAMutableURLRequest *)oRequest{
	//[oRequest setOAuthParameterName:@"oauth_callback" withValue:authorizeCallbackURL.absoluteString];
}
- (void)tokenAccessModifyRequest:(OAMutableURLRequest *)oRequest{	
	[oRequest setOAuthParameterName:@"oauth_verifier" withValue:[self.authorizeResponseQueryVars objectForKey:@"oauth_verifier"]];
}

- (void)tokenAccessTicket:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data {
	/*if (xAuth) 
	 {
	 if (ticket.didSucceed)
	 {
	 [item setCustomValue:[[pendingForm formValues] objectForKey:@"followMe"] forKey:@"followMe"];
	 [pendingForm close];
	 }
	 
	 else
	 {
	 [self tokenAccessTicket:ticket didFailWithError:[SHK error:[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]]];
	 return;
	 }
	 }
	 else
	 {
	 if (ticket.didSucceed)
	 {
	 if (delegate){
	 [delegate recievedDidSucceed];
	 }
	 }
	 }*/
	[super tokenAccessTicket:ticket didFinishWithData:data];		
}


#pragma mark -
#pragma mark UI Implementation

- (void)show{
	if (item.shareType == SHKShareTypeURL){
		[self shortenURL];
	}else if (item.shareType == SHKShareTypeImage){
		[item setCustomValue:item.title forKey:@"status"];
		[self showSohuForm];
	}else if (item.shareType == SHKShareTypeText){
		[item setCustomValue:item.text forKey:@"status"];
		[self showSohuForm];
	}
}

- (void)showSohuForm{
	SHKSohuForm *rootView = [[SHKSohuForm alloc] initWithNibName:nil bundle:nil];	
	rootView.delegate = self;
	
	// force view to load so we can set textView text
	[rootView view];
	
	rootView.textView.text = [item customValueForKey:@"status"];
	rootView.hasAttachment = item.image != nil;
	
	[self pushViewController:rootView animated:NO];
	
	[[SHK currentHelper] showViewController:self];	
}

- (void)sendForm:(SHKSohuForm *)form{	
	[item setCustomValue:form.textView.text forKey:@"status"];
	[self tryToSend];
}


#pragma mark -

- (void)shortenURL{	
	if (![SHK connected]){
		[item setCustomValue:[NSString stringWithFormat:@"%@ %@", item.title, [item.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] forKey:@"status"];
		[self showSohuForm];		
		return;
	}
	
	if (!quiet)
		[[SHKActivityIndicator currentIndicator] displayActivity:SHKLocalizedString(@"Shortening URL...")];
	
	self.request = [[[SHKRequest alloc] initWithURL:[NSURL URLWithString:[NSMutableString stringWithFormat:@"http://api.bit.ly/v3/shorten?login=%@&apikey=%@&longUrl=%@&format=txt",
																		  SHKBitLyLogin,
																		  SHKBitLyKey,																		  
																		  SHKEncodeURL(item.URL)
																		  ]]
											 params:nil
										   delegate:self
								 isFinishedSelector:@selector(shortenURLFinished:)
											 method:@"GET"
										  autostart:YES] autorelease];
}

- (void)shortenURLFinished:(SHKRequest *)aRequest{
	[[SHKActivityIndicator currentIndicator] hide];
	
	NSString *result = [[aRequest getResult] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
	
	if (result == nil || [NSURL URLWithString:result] == nil){
		// TODO - better error message
		[[[[UIAlertView alloc] initWithTitle:SHKLocalizedString(@"Shorten URL Error")
									 message:SHKLocalizedString(@"We could not shorten the URL.")
									delegate:nil
						   cancelButtonTitle:SHKLocalizedString(@"Continue")
						   otherButtonTitles:nil] autorelease] show];
		
		[item setCustomValue:[NSString stringWithFormat:@"%@ %@", item.title, [item.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] forKey:@"status"];
	}
	
	else
		[item setCustomValue:[NSString stringWithFormat:@"%@ %@", item.title, result] forKey:@"status"];
	
	[self showSohuForm];
}


#pragma mark -
#pragma mark Share API Methods

- (BOOL)validate{
	NSString *status = [item customValueForKey:@"status"];
	return status != nil && status.length >= 0 && status.length <= 140;
}

- (BOOL)send{	
	
	if (![self validate]){
		[self show];
	}else{	
		//if (item.shareType == SHKShareTypeImage)
		//	[self sendImage];
		
		//else
		[self sendStatus];
		
		
		// Notify delegate
		[self sendDidStart];	
		
		return YES;
	}
	
	return NO;
}

- (void)sendStatus{
	
	OAMutableURLRequest *oRequest = [[OAMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://api.t.sohu.com/statuses/update.json"]
																	consumer:consumer
																	   token:accessToken
																	   realm:nil
														   signatureProvider:nil];
	
	[oRequest setHTTPMethod:@"POST"];
	
	OARequestParameter *statusParam = [[OARequestParameter alloc] initWithName:@"status"
																		 value:[item customValueForKey:@"status"]];
	NSArray *params = [NSArray arrayWithObjects:statusParam, nil];
	[oRequest setParameters:params];
	[statusParam release];
	
	OAAsynchronousDataFetcher *fetcher = [OAAsynchronousDataFetcher asynchronousFetcherWithRequest:oRequest
																						  delegate:self
																				 didFinishSelector:@selector(sendStatusTicket:didFinishWithData:)
																				   didFailSelector:@selector(sendStatusTicket:didFailWithError:)];	
	
	[fetcher start];
	[oRequest release];
	
}

- (void)sendStatusTicket:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data {	
	// TODO better error handling here
	
	if (ticket.didSucceed) {
		[self sendDidFinish];
	}else{
		NSString *error = [[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
		NSLog(@"================error:%@",error);
        [error release];
		[self sendDidFailWithError:nil];
	}
}

- (void)sendStatusTicket:(OAServiceTicket *)ticket didFailWithError:(NSError*)error{
	NSLog(@"sohu update status error:%@",error);
	[self sendDidFailWithError:error];
}

/*
- (void)followMe
{
	// remove it so in case of other failures this doesn't get hit again
	[item setCustomValue:nil forKey:@"followMe"];
	
	OAMutableURLRequest *oRequest = [[OAMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://api.twitter.com/1/friendships/create/%@.json", SHKTwitterUsername]]
																	consumer:consumer
																	   token:accessToken
																	   realm:nil
														   signatureProvider:nil];
	
	[oRequest setHTTPMethod:@"POST"];
	
	OAAsynchronousDataFetcher *fetcher = [OAAsynchronousDataFetcher asynchronousFetcherWithRequest:oRequest
																						  delegate:nil // Currently not doing any error handling here.  If it fails, it's probably best not to bug the user to follow you again.
																				 didFinishSelector:nil
																				   didFailSelector:nil];	
	
	[fetcher start];
	[oRequest release];
}*/

@end